package com.snail.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.core.util.IdUtil;
import com.snail.result.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.awt.Font;

/**
 * 验证码服务类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CaptchaService {
    
    private final StringRedisTemplate stringRedisTemplate;
    
    private static final String CAPTCHA_PREFIX = "captcha:";
    private static final long CAPTCHA_EXPIRE = 300; // 验证码过期时间(秒)
    
    /**
     * 生成图片验证码
     * @return 验证码信息
     */
    public Result<Map<String, String>> generateCaptcha() {
        // 生成唯一标识符
        String uuid = IdUtil.simpleUUID();
        String key = CAPTCHA_PREFIX + uuid;
        
        // 设置验证码图片长、宽、验证码字符数、干扰线宽度
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(120, 45, 1, 10);
        // 设置字体样式和大小
        lineCaptcha.setFont(new Font("Arial", Font.BOLD, 40));
        
        // 获取生成的验证码
        String captcha = lineCaptcha.getCode();
        
        // 存储到Redis中
        stringRedisTemplate.opsForValue().set(
            key,
            captcha, 
            CAPTCHA_EXPIRE, 
            TimeUnit.SECONDS
        );
        
        log.info("生成验证码: key={}, captcha={}", key, captcha);

        Map<String, String> result = new HashMap<>();
        // 转为Base64字符串
        String imageBase64 = lineCaptcha.getImageBase64Data();
        result.put("captchaKey", uuid);
        result.put("base64Code", imageBase64);
        return Result.success(result);
    }
    
    /**
     * 验证验证码
     * @param key 验证码key
     * @param captcha 用户输入的验证码
     * @return 验证结果
     */
    public boolean validateCaptcha(String key, String captcha) {
        if (StrUtil.isBlank(key) || StrUtil.isBlank(captcha)) {
            return false;
        }
        
        String redisKey = CAPTCHA_PREFIX + key;
        String storedCaptcha = stringRedisTemplate.opsForValue().get(redisKey);
        
        if (StrUtil.isBlank(storedCaptcha)) {
            return false;
        }
        
        boolean isValid = storedCaptcha.equalsIgnoreCase(captcha);
        
        // 验证成功后删除验证码
        if (isValid) {
            stringRedisTemplate.delete(redisKey);
        }
        
        log.info("验证验证码: key={}, captcha={}, isValid={}", key, captcha, isValid);
        return isValid;
    }
}